package 动态规划;

public class 零钱兑换 {
	public static void main(String[] args) {
		System.out.println(coins(19, new int[]{5, 20, 25}));
	}
	
	

	/**
	 * 暴力递归(自顶向下)
	 */
	public static int coin1(int n) {
		if (n < 1) return Integer.MAX_VALUE;
		if (n == 1 || n == 5 || n == 20 || n == 25) return 1;
		int min1 = Math.min(coin1(n - 1), coin1(n - 5));
		int min2 = Math.min(coin1(n - 20), coin1(n - 25));
		return Math.min(min1, min2) + 1;
		
	}

	/**
	 * 记忆化搜索(自顶向下)
	 */
	public static int coin2(int n) {
	
		int[] dp = new int[n + 1];
		int[] faces = new int[]{1, 5, 20, 25};
		for (int face : faces) {
			if (face > n) break;
			dp[face] = 1;
		}
		coin2(n , dp);
		return coin2(n, dp);
	}
	
	private static int coin2(int n, int[] dp) {
		if (n < 1) return Integer.MAX_VALUE;
		if (dp[n] == 0) {
			int min1 = Math.min(coin2(n - 1, dp), coin2(n - 5, dp));
			int min2 = Math.min(coin2(n - 20, dp), coin2(n - 25, dp));
			dp[n] = Math.min(min1, min2) + 1;
		}
		return dp[n];
	} 
	
	/**
	 * 递推(自底向上)
	 */
	public static int coin3(int n) {
		if (n < 1) return -1;
		int[] dp = new int[n + 1];
		for (int i = 1; i < dp.length; i++) {
			int min = dp[i - 1];
			if (i >= 5) min = Math.min(dp[i - 5], min);
			if (i >= 20) min = Math.min(dp[i - 20], min);
			if (i >= 25) min = Math.min(dp[i - 25], min);
			
			dp[i] = min + 1;
		}
		return dp[n];
	}
	
	/**
	 * 列出找钱方案
	 */
	public static int coin4(int n) {
		if (n < 1) return -1;
		int[] dp = new int[n + 1];
		int[] faces = new int[n + 1];	// 记录找n钱时, 最后一块拿的硬币
		for (int i = 1; i < dp.length; i++) {
			int min = dp[i - 1];
			faces[i] = 1;
			if (i >= 5 && dp[i - 5] < min) {
				min = dp[i - 5];
				faces[i] = 5;
			} 
			if (i >= 20 && dp[i - 20] < min) {
				min = dp[i - 20];
				faces[i] = 20;
			} 
			if (i >= 25 && dp[i - 25] < min) {
				min = dp[i - 25];
				faces[i] = 25;
			} 
			dp[i] = min + 1;
		}
		print(n, faces);
		return dp[n];
	}
	
	private static void print(int n, int[] faces) {
		System.out.println("-----------"+n+"------------");
		while (n > 0) {
			System.out.print(faces[n] + " ");
			n -= faces[n];
		}
	}
	
	/**
	 * 通用实现
	 */
	public static int coins(int n, int[] faces) {
		if (n < 1 || faces == null || faces.length == 0) return -1;
		int[] dp = new int[n + 1];
		for (int i = 1; i < dp.length; i++) {
			int min = Integer.MAX_VALUE;
			for (int face : faces) {
				if (i < face || dp[i - face] == -1) continue;
				min = Math.min(min, dp[i - face]);
			}
			if (min == Integer.MAX_VALUE) {
				dp[i] = -1;
			} else {
				dp[i] = min + 1;
			}
		}
		return dp[n];
	}
}
